package com.shyroke.daydayzhuanweb.controller;

import cn.hutool.core.util.StrUtil;
import com.shyroke.daydayzhuanapi.dto.AdminUserDto;
import com.shyroke.daydayzhuanapi.dto.AdminUserRequest;
import com.shyroke.daydayzhuanapi.dto.NewsDto;
import com.shyroke.daydayzhuanapi.dto.UserMain;
import com.shyroke.daydayzhuanapi.entity.UserEntity;
import com.shyroke.daydayzhuandao.respository.UserRepository;
import com.shyroke.daydayzhuansvc.service.INewsService;
import com.shyroke.daydayzhuansvc.service.impl.OSSService;
import com.shyroke.daydayzhuansvc.service.impl.UserService;
import com.shyroke.daydayzhuansvc.util.OSSClientConstants;
import com.shyroke.daydayzhuansvc.util.Page;
import com.shyroke.daydayzhuansvc.util.R;
import com.shyroke.daydayzhuansvc.util.TabelData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.net.URLDecoder;
import java.util.Optional;

/**
 * 类名 ：
 * 用法 ：
 * 创建人 ： shyroke
 * 时间：2018/12/28 12:38
 */
@Controller
@RequestMapping(value = "admin/user")
public class AdminUserController {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private UserRepository userRepository;
    @Autowired
    private INewsService newsService;
    @Autowired
    private OSSService ossService;
    @Autowired
    private UserService userService;

    /**
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "desc")
    public ModelAndView free_list(ModelAndView model,HttpSession session) {
        UserMain user = (UserMain)session.getAttribute("user");
        Optional<UserEntity> optionalUser = userRepository.findById(user.getId());
        model.addObject("user",optionalUser.get());
        model.setViewName("admin/user/desc");

        return model;
    }

    /**
     * 保存免费项目
     * @param user
     * @return
     */
    @RequestMapping(value = "update")
    @ResponseBody
    public R update(@RequestBody UserEntity user, HttpSession session){
        try {
            if(StrUtil.isNotBlank(user.getPay())){
                String pay = URLDecoder.decode(user.getPay(),"utf-8");
                if(pay != null && !pay.startsWith(OSSClientConstants.COVER_PATH)){
                    user.setPay(pay.substring(pay.indexOf(OSSClientConstants.COVER_PATH)));
                }
            }
            if(StrUtil.isNotBlank(user.getTouxiang())){
                String touxiang = URLDecoder.decode(user.getTouxiang(),"utf-8");
                if(touxiang != null && !touxiang.startsWith(OSSClientConstants.COVER_PATH)){
                    user.setTouxiang(touxiang.substring(touxiang.indexOf(OSSClientConstants.COVER_PATH)));
                }
            }
            Optional<UserEntity> optionalUser = userRepository.findById(user.getId());
            if (optionalUser.isPresent()) {
                UserEntity userEntity = optionalUser.get();
                if(StrUtil.isNotBlank(user.getPassword())){
                    userEntity.setPassword(user.getPassword());
                }
                if(StrUtil.isNotBlank(user.getName())){
                    userEntity.setName(user.getName());
                }
                if(StrUtil.isNotBlank(user.getAuthor())){
                    userEntity.setAuthor(user.getAuthor());
                }
                if(StrUtil.isNotBlank(user.getEmail())){
                    userEntity.setEmail(user.getEmail());
                }
                if(StrUtil.isNotBlank(user.getTouxiang())){
                    userEntity.setTouxiang(user.getTouxiang());
                }
                if(StrUtil.isNotBlank(user.getPay())){
                    userEntity.setPay(user.getPay());
                }
                if(StrUtil.isNotBlank(user.getRealName())){
                    userEntity.setRealName(user.getRealName());
                }
                if(user.getStatus() != null){
                    userEntity.setStatus(user.getStatus());
                }
                userRepository.save(userEntity);
            }
        }catch (Exception e){
            logger.info("保存失败",e);
            return R.error("保存失败");
        }
        return R.ok("保存成功！");
    }

    /**
     * 跳转到个人资料页面
     * @param model
     * @return
     */
    @RequestMapping(value = "changeInfo")
    public ModelAndView changeInfo(ModelAndView model,HttpSession session) {
        UserMain user = (UserMain)session.getAttribute("user");
        Optional<UserEntity> optionalUser = userRepository.findById(user.getId());
        if(optionalUser.isPresent()){
            UserEntity user1 = optionalUser.get();
            if(!StringUtils.isEmpty(user1.getTouxiang())){
                user1.setTouxiang(ossService.getImgUrl(user1.getTouxiang()));
            }
            if(!StringUtils.isEmpty(user1.getPay())){
                user1.setPay(ossService.getImgUrl(user1.getPay()));
            }
            model.addObject("user",user1);
        }
        model.setViewName("admin/user/desc");
        return model;
    }

    /**
     * 跳转到消息通知
     * @param model
     * @return
     */
    @RequestMapping(value = "newsList")
    public ModelAndView newsList(ModelAndView model,HttpSession session) {
        model.setViewName("admin/user/newList");
        return model;
    }

    /**
     * 获取消息分页数据
     * @param page
     * @param isRead
     * @param session
     * @return
     */
    @RequestMapping(value = "getNewsTableData")
    @ResponseBody
    public TabelData<NewsDto> getNewsTableData(Page page, Integer isRead, HttpSession session){
        UserMain user = (UserMain)session.getAttribute("user");
        return newsService.getTableDate(page,isRead,user);
    }

    /**
     * 阅读消息
     * @return
     */
    @RequestMapping(value = "readNews")
    @ResponseBody
    public R readNews(Integer id){
        try {
            newsService.readNews(id);
            return R.ok("消息查看成功！");
        }catch (Exception e){
            logger.info("消息更新失败",e);
            return R.error("消息更新失败！");
        }
    }

    /**
     * 跳转用户列表页面
     * @param model
     * @return
     */
    @RequestMapping(value = "listView")
    public ModelAndView listView(ModelAndView model,HttpSession session){
        model.setViewName("admin/user/list");
        return model;
    }

    @GetMapping("list")
    @ResponseBody
    public TabelData<AdminUserDto> list(Page page,AdminUserRequest request){
        return userService.list(page,request);
    }

}
